<template>
  <div>
    <el-upload
      action="uploadAction"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :before-remove="handleBeforeRemove"
      :data="data"
      multiple
      :show-file-list="true"
      ref="upload"
      :accept="acceptType"
      :on-error="uploadError"
      :file-list="fileLists"
      :on-change="changeFile"
      :before-upload="beforeAvatarUpload"
      :http-request="()=>{}"
      :disabled="disabled"
      :class="{ 'info-upload': historyInfo }"
    >
        <i class="el-icon-plus"></i>
        <div slot="tip" class="el-upload__tip">只能上传{{acceptType}}文件</div>
    </el-upload>
    <el-dialog :visible.sync="imgVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import pdfImg from '@/assets/images/pdf.png'
import wordImg from '@/assets/images/word.png'
import xlsxImg from '@/assets/images/xlsx.png'
import {
  getSimpleFilePreview
} from "@/api/common";
export default {
  name: 'uploadImage',
  props: ['acceptType', 'historyInfo', 'attachments', 'fileLists', 'disabled', 'data', 'currentItem', 'beforeRemove'],
  data() {
    return {
      dialogImageUrl: null,
      imgVisible: false,
      testArr: this.fileLists,
    }
  },
  watch: {
    fileLists: {
      handler(val) {
        this.testArr = val
      },
      deep: true, // 深度监听
      immediate: true, // 初次监听即执行
    }
  },
  created(){
  },
  computed:{
  },
  methods:{
    // 图片上传失败时
    uploadError() {
      this.$message.error("图片上传失败!");
    },
    //预览图片
    handlePictureCardPreview(file) {
      const fileId = file.fileId || null;
      console.log("handlePictureCardPreview:",fileId);
      if(!fileId){
        this.$message({
          showClose: true,
          message: '未保存，不能预览',
          type: 'warning'
        });
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      var fileType = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
      getSimpleFilePreview({fileId}).then(response => {
        loading.close();
        if(response.code == 200){
          const path = response.path;
          if (fileType == ".png" || fileType == ".webp" || fileType == ".jpg" || fileType == '.jpeg') {
            this.dialogImageUrl = path; // PC端使用path预览，APP端使用
            this.imgVisible = true;
          } else{ // pdf word xlsx文件预览
            let url = this.$router.resolve({
              path:"/scanPdf",
              query:{url:path}
            })
            window.open(url.href, '_blank');
          }
        }else{
          this.msgError('预览失败');
        }
      },err=>{
        console.log("err:",err);
        loading.close();
      })
    },
    handleRemove(file, fileList) {
      let tmpArr = this.attachments.concat();
      let tmpList = [];
      fileList.forEach((ele)=>{
        for(let i=0; i<tmpArr.length; i++){
          if(tmpArr[i].fileName == ele.name){
            tmpList.push(tmpArr[i]);
            break;
          }
        }
      });
      this.testArr = fileList;
      this.$emit('remove', file, this.currentItem);

      this.$emit('change', tmpList, this.currentItem, 'delete');
      this.$emit('saveFile', fileList, this.currentItem, 'delete');
    },
    handleBeforeRemove(file, fileList) {
      if (Object.prototype.toString.call(this.beforeRemove) === "[object Function]") {
        return this.beforeRemove(file, fileList)
      }
      return true
    },
    beforeAvatarUpload(file) {
      // // 文件格式判断
      let flag = this.handleBeforeUpload(file);
      if (!flag) {
        return false;
      }
      // 文件名称长度判断
      let flagName = this.handleBeforeName(file);
      if (!flagName) {
        return false;
      }
    },
    changeFile(option, fileList) {
      const file = option.raw;
      let flag = this.handleBeforeUpload(file, false);
      if (!flag) {
        return;
      }
      // 文件名称长度判断
      let flagName = this.handleBeforeName(file, false);
      if (!flagName) {
        return;
      }
      // 文件base64
      this.saveImgBase64(option);
      // 文件保存fileLists
      this.saveFileLists(option);
    },
    handleBeforeUpload(file, boolValue) {
      let fileType = file.name.substring(file.name.lastIndexOf('.')+1).toLowerCase();
      let isType = true;
      let acceptTypeArr = this.acceptType.replace(/\s*/g,"").replace(/\./g,"").split(',');
      // if(acceptTypeArr.includes(fileType))
      // if (!(fileType == 'jpg' || fileType == 'png')) {
      //   isType = false;
      //   if(boolValue == false) return;
      //   this.$message.error({
      //     message: '请上传格式为.jpg, .png'
      //   })
      // }
      if (!acceptTypeArr.includes(fileType)) {
        isType = false;
        if(boolValue == false) return;
        let message = '请上传格式为.jpg, .png';
        this.$message.error({
          message: this.acceptType || message
        })
      }
      return isType;
    },
    handleBeforeName(file, boolValue) {
      let fileName = file.name.substring(0, file.name.lastIndexOf('.'));
      let isType = true;
      if (!(fileName.length <= 200)) {
        isType = false;
        if(boolValue == false) return;
        this.$message.error({
          message: '文件名过长，请修改提交'
        })
      }
      return isType;
    },
    saveImgBase64(option) {
      let file = option.raw;
      let _this = this;
      let { name:fileName, type:fileType } = file;
      let tmpObj = {
        fileBase64: "",
        fileName:fileName.toLowerCase(),
        fileType,
        fileUrl: ""
      };
      let rd = new FileReader(); // 创建文件读取对象
      rd.readAsDataURL(file) // 文件读取装换为base64类型
      let tmpArr = this.currentItem ? [] : this.attachments;
      rd.onloadend = function (e) {
        let arr1 = this.result.split(',');
        tmpObj.fileBase64Prefix = arr1[0];
        tmpObj.fileBase64 = arr1[1];
        tmpArr.push(tmpObj);
        _this.$emit('change', tmpArr, _this.currentItem);
      }
    },
    saveFileLists(option) {
      let listObj = this.fileListObj(option);
      let arr = this.testArr.concat();
      arr.push(listObj);
      this.testArr = arr;
      this.$emit('saveFile', arr, this.currentItem, listObj);
    },
    fileListObj(option) {
      let file = option.raw;
      let fileType = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
      let url = '';
      let realurl = option.url;
      if (fileType == ".pdf") {
        url = pdfImg;
      } else if (fileType == ".png" || fileType == ".jpg" || fileType == '.jpeg') {
        url = option.url;
      } else if (fileType == ".doc" || fileType == ".docx") {
        url = wordImg;
      } else if (fileType == '.xls' || fileType == '.xlsx') {
        url = xlsxImg;
      }
      let { name:fileName } = file;
      let listObj = {
        name: fileName.toLowerCase(),
        url,
        realurl
      };
      return listObj;
    },
  },
}
</script>
<style scoped lang="less" scoped>
.info-upload{
  /deep/.el-upload--picture-card{
    display: none;
  }
}
/deep/.el-upload{
  margin: 5px;
  margin-left: 0;
}
</style>
